package xin.lhuo.we.server.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xin.lhuo.we.server.entity.User;
import xin.lhuo.we.server.exception.WeException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static xin.lhuo.we.server.constant.HttpConstant.SESSION_USER;
import static xin.lhuo.we.server.constant.HttpConstant.TOKEN;
import static xin.lhuo.we.server.enums.ResultEnum.*;

/**
 * @author Lhuo
 * @date 2019/5/5 11:40
 */

@Aspect
@Component
@Slf4j
public class AuthorizeAspect {
    @Pointcut("execution(public * xin.lhuo.we.server.controller..*.*(..))" +
            "&& !execution(public * xin.lhuo.we.server.controller.user.UserController.register(..))" +
            "&& !execution(public * xin.lhuo.we.server.controller.user.UserController.login(..))"+
    "&& !execution(public * xin.lhuo.we.server.controller.user.PhotoController.uploadCallback(..))"+
            "&& !execution(public * xin.lhuo.we.server.controller.user.TestController.test(..)) " +
            "&& !execution(* xin.lhuo.we.server.controller.user.DocumentController.uploadCallback(..))")
    public void Verify() {
    }

    @Before("Verify()")
    public void doBefore() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String token = request.getHeader(TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new WeException(TOKEN_IS_NULL);
        }
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute(SESSION_USER);
        log.debug("user {}",user);
        if (user == null || StringUtils.isEmpty(user.getToken())) {
            throw  new WeException(NOT_LOGIN);
        }
        if (!token.equals(user.getToken())) {
            throw new WeException(TOKEN_ERROR);
        }
    }
}
